package com.sjtu.network.chatanalysis.openai;


import com.sjtu.network.chatanalysis.openai.entity.chat.ChatCompletion;
import com.sjtu.network.chatanalysis.openai.entity.chat.ChatCompletionResponse;
import com.sjtu.network.chatanalysis.openai.entity.chat.Message;
import com.sjtu.network.chatanalysis.util.Proxys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.net.Proxy;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class ChatGPTUtil implements InitializingBean {
    @Value("${openai.secret_key}")
    private String token;

    private ChatGPT chatGPT;

    @Value("${proxy.ip}")
    private String proxyIp;
    @Value("${proxy.port}")
    private Integer proxyPort;

    @Override
    public void afterPropertiesSet() throws Exception {
        if(!StringUtils.isEmpty(proxyIp)){
            //如果在国内访问，使用这个,在application.yml里面配置
            Proxy proxy = Proxys.http(proxyIp, proxyPort);
            chatGPT = ChatGPT.builder()
                    .apiKey(token)
                    .timeout(600)
                    .proxy(proxy)
                    .apiHost("https://api.openai.com/") //代理地址
                    .build()
                    .init();
        }else{
            chatGPT = ChatGPT.builder()
                    .apiKey(token)
                    .timeout(600)
                    .apiHost("https://api.openai.com/") //代理地址
                    .build()
                    .init();
        }
    }


    public List<Message> chatAnalysis(String userMessage) {
        Message systemMessage = Message.ofSystem("假设有AB两个人在相亲，你需要根据A说的每一句来判断A对B是否有好感，并给出一个数据结果，初始数据为500，满分1000，增减从-10到10，-10代表非常反感，0代表感情中立，10代表非常有好感。如果你认为A在对B表白，则可以直接给出满分。你无需对B的话打分。");
        Message msg = Message.of(userMessage);
        return Arrays.asList(systemMessage, msg);
    }

    public Message chat(String userMessage,String user) {
        List<Message> messages = chatAnalysis(userMessage);

        ChatCompletion chatCompletion = ChatCompletion.builder()
                .model(ChatCompletion.Model.GPT_3_5_TURBO.getName())
                .user(user)
                .messages(messages)
                .maxTokens(3000)
                .temperature(0.9)
                .build();
        ChatCompletionResponse response = chatGPT.chatCompletion(chatCompletion);
        return response.getChoices().get(0).getMessage();
    }

}
